package top.zerozoo.learn.grade.dao.impl;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import top.zerozoo.learn.grade.dao.StudentBaseInfoDao;
import top.zerozoo.learn.grade.entity.StudentBaseInfo;
import top.zerozoo.learn.grade.util.JdbcUtils;

import java.util.*;

public class StudentBaseInfoDaoImpl implements StudentBaseInfoDao {

    private JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());


    @Override
    public int count(Map<String, String> condition) {
        StringBuilder strBuilder = new StringBuilder("select count(*) from student_baseinfo where 1 = 1");
        List<Object> param = new LinkedList<>();

        Iterator<Map.Entry<String, String>> iterator = condition.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            if(next.getValue() == null || next.getValue().isEmpty())
            {
                continue;
            }
            strBuilder.append(" and "+next.getKey()+" like ?");
            param.add(next.getValue());
        }
        return template.queryForObject(strBuilder.toString(),Integer.class,param.toArray());
    }


    @Override
    public List<StudentBaseInfo> find(int start, int rows, Map<String, String> condition) {
        StringBuilder strBuilder = new StringBuilder("select * from student_baseinfo where 1 = 1");
        List<Object> param = new LinkedList<>();

        Iterator<Map.Entry<String, String>> iterator = condition.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            if(next.getValue() == null || next.getValue().isEmpty())
            {
                continue;
            }
            strBuilder.append(" and "+next.getKey()+" like ?");
            param.add(next.getValue());
        }
        strBuilder.append(" limit "+start+","+rows);
        return template.query(strBuilder.toString(),new BeanPropertyRowMapper<>(StudentBaseInfo.class),param.toArray());
    }


}
